package com.ytt.core.api.security;

import com.ytt.core.model.user.UserDto;
import com.ytt.core.service.exception.NoSuchDataException;
import com.ytt.core.service.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * LocalDatabaseUserDetailsServiceImpl
 * 本地数据库方式的用户服务
 * @author chenwen
 * @date 2019/9/12 16:02
 */
public class LocalDatabaseUserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            String userId = userService.findByAccount(username);
            UserDto userDTO = userService.findById(userId);

            return new CurrentUser(userDTO);
        } catch (NoSuchDataException e) {
            throw new UsernameNotFoundException(String.format("找不到用户：%s", e));
        }
    }
}
